#!/bin/bash

# Java 编译器脚本
# 生成一个可执行的脚本来使得运行 java 程序和本地程序一致

DEST="$1"; shift
MAINSOURCE="$1"

if [ -z "$ENTRY_POINT" ]; then
    MAINCLASS="Main.java"
else
    MAINCLASS="$ENTRY_POINT"
fi

# 将类似 java/lang/String.java 转换为 java.lang.String
MAINCLASS=${MAINCLASS%.*}
MAINCLASS=${MAINCLASS//\//.}

javac -encoding UTF-8 -sourcepath . -d . "$@"
EXITCODE=$?
[ "$EXITCODE" -ne 0 ] && exit $EXITCODE

# Check if entry point exists
javap "$MAINCLASS" > /dev/null
EXITCODE=$?
[ "$EXITCODE" -ne 0 ] && exit $EXITCODE

cat > "$DEST" <<EOF
#!/bin/sh
# 运行路径不一定是编译目录，因此我们需要切换到编译目录下运行，否则会找不到文件
if [ "\${0%/*}" != "\$0" ]; then
	cd "\${0%/*}"
fi

MEMSTACK=65536
MEMJVM=65536
MEMRESERVED=\$((MEMSTACK + MEMJVM))
MEMLIMITJAVA=\$((MEMLIMIT - MEMRESERVED))

if [ -z "\$MEMLIMIT" ]; then
    exec java -DONLINE_JUDGE -Dfile.encoding=UTF-8 -XX:+UseSerialGC -Xss\${MEMSTACK}k '$MAINCLASS' "\$@"
else
    exec java -DONLINE_JUDGE -Dfile.encoding=UTF-8 -XX:+UseSerialGC -Xss\${MEMSTACK}k -Xms\${MEMLIMITJAVA}k -Xmx\${MEMLIMITJAVA}k '$MAINCLASS' "\$@"
fi
EOF

chmod a+x "$DEST"
exit 0